package com.zhaoyue.study.concurrency.forkjoin;

import com.sun.org.apache.xalan.internal.utils.FeatureManager;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 2016/12/6
 * Time: 15:25
 * To change this template use File | Settings | File Templates.
 */
public class CountTask  extends RecursiveTask{

    private static final int FAZHI = 2;
    private int start;
    private int end;

    public CountTask(int start,int end){
        this.start = start;
        this.end = end;
    }

    @Override
    protected Object compute() {
        int sum = 0;
        boolean canCompute = end - start <= FAZHI;
        if(canCompute){
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        }else {
            //如果超出阀值则继续拆分
            int middle = (start + end) / 2;
            CountTask leftTast = new CountTask(start,middle);
            CountTask rightTask = new CountTask(middle+1,end);
            leftTast.fork();
            rightTask.fork();

            int leftResult = (int)leftTast.join();
            int rightResult = (int)rightTask.join();
            sum = leftResult + rightResult;
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        long begin = System.nanoTime();
        CountTask countTask = new CountTask(1,100000);
        Future<Integer> future =  forkJoinPool.submit(countTask);
        long cost = System.nanoTime() - begin;
        System.out.println(future.get());
        System.out.println("cost:" + cost);

        begin = System.nanoTime();
        int sum = 0;
        for (int i = 1; i <= 100000; i++) {
            sum += i;
        }
        cost = System.nanoTime() - begin;
        System.out.println(sum);
        System.out.println("cost:" + cost);

    }
}
